package server

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/yuya000/cards-game-server-go/logwarp"
	"github.com/garyburd/redigo/redis"
	"time"
)

var (
	UserLoginStatusNotFound = errors.New("玩家没有登录状态")
	UserNotFound            = errors.New("用户没有找到")
	ClubNotFound            = errors.New("俱乐部没有找到")
)

type LoginStatus struct {
	Uid string `json:"uid"`
}

type User struct {
	Id                  string    `xorm:"id pk"`
	No                  string    `xorm:"no"`
	NickName            string    `xorm:"nickname"`
	Avatar              string    `xorm:"avatar"`
	Title               string    `xorm:"title"`
	CreateTime          time.Time `xorm:"create_time"`
	WXOpenId            string    `xorm:"wx_open_id"`
	WXUnionId           string    `xorm:"wx_union_id"`
	CurrentClubId       string    `xorm:"current_club_id"`
	CurrentClubName     string    `xorm:"current_club_name"`
	AccessToken         string    `xorm:"access_token"`
	GamesInnings        int       `xorm:"games_innings"`
	NiuNiuInnings       int       `xorm:"niuniu_innings"`
	GamesWinInnings     int       `xorm:"games_win_innings"`
	NiuNiuWinInnings    int       `xorm:"niuniu_win_innings"`
	NiuNiuWinRate       int       `xorm:"niuniu_win_rate"`
	Score               int       `xorm:"score"`
	Credit              int       `xorm:"credit"`
	TitleDisplay        int       `xorm:"title_display"`
	CostHouseCards      int       `xorm:"cost_house_cards"`
	PaoDeKuaiInnings    int       `xorm:"paodekuai_innings"`
	PaoDeKuaiWinInnings int       `xorm:"paodekuai_win_innings"`
	PaoDeKuaiWinRate    int       `xorm:"paodekuai_win_rate"`
}

func (u *User) ToUserInfoEntry() *UserInfoEntry {
	return &UserInfoEntry{
		Id:               u.Id,
		NickName:         u.NickName,
		Avatar:           u.Avatar,
		No:               u.No,
		Title:            u.Title,
		CurrentClubId:    u.CurrentClubId,
		CurrentClubName:  u.CurrentClubName,
		GamesInnings:     u.GamesInnings,
		GamesWinInnings:  u.GamesWinInnings,
		NiuNiuInnings:    u.NiuNiuInnings,
		NiuNiuWinInnings: u.NiuNiuWinInnings,
		NiuNiuWinRate:    u.NiuNiuWinRate,
		Score:            u.Score,
		TitleDisPlay:     u.TitleDisplay,
	}
}

type CurrentClub struct {
	Id              string    `xorm:"id pk"`
	Uid             string    `xorm:"uid"`
	ClubId          string    `xorm:"club_id"`
	ClubNo          string    `xorm:"no"`
	ClubName        string    `xorm:"club_name"`
	HouseCards      int       `xorm:"house_cards"`
	VipDays         int       `xorm:"vip_days"`
	VipBuyDate      time.Time `xorm:"vip_buy_date null"`
	CreateTime      time.Time `xorm:"create_time"`
	Intro           string    `xorm:"intro"`
	VipGiftLastTime time.Time `xorm:"vip_gift_last_time null"`
	ReceiveNoticeNo int       `xorm:"receive_notice_no"`
	VipTitleDisplay int       `xorm:"vip_title_display"`
}

func (c *CurrentClub) ToClubInfoEntry() *ClubInfoEntry {
	return &ClubInfoEntry{
		Id:              c.Id,
		No:              c.ClubNo,
		Name:            c.ClubName,
		VipDays:         c.VipDays,
		HouseCards:      c.HouseCards,
		Introduction:    c.Intro,
		VipTitleDisplay: c.VipTitleDisplay,
	}
}

func UserLoginStatus(token string) (*LoginStatus, Exception) {
	accessTokenBuffer, err := redis.Bytes(RedisPool.Get().Do("GET", fmt.Sprintf("%s%s", AccessTokenPrefix, token)))
	if err == redis.ErrNil {
		logwarp.Std().Warningln("没有token信息", token)
		return nil, NeedLoginException
	} else if err != nil {
		logwarp.Std().Warningln(err)
		return nil, SystemException
	}
	ls := &LoginStatus{}
	if err := json.Unmarshal(accessTokenBuffer, ls); err != nil {
		logwarp.Std().Warningln(err)
		return nil, SystemException
	}
	return ls, nil
}

func (u *User) TableName() string {
	return "users"
}

func UserInfoByUid(uid string) (*User, Exception) {
	var u User
	exist, err := DBEngine.ID(uid).Get(&u)
	if err != nil {
		logwarp.Std().Warningln(err)
		return nil, SystemException
	}
	if !exist {
		logwarp.Std().Warningln(uid, err)
		return nil, InvalidOptException
	}
	return &u, nil
}

func (cc *CurrentClub) TableName() string {
	return "users_clubs"
}

func CurrentClubInfo(uid, clubId string) (*CurrentClub, Exception) {
	if clubId == "" {
		logwarp.Std().Warningln("非法操作 没有加入任何俱乐部", uid, clubId)
		return nil, InvalidOptException
	}
	var cc CurrentClub
	exist, err := DBEngine.Where("uid=?", uid).And("club_id=?", clubId).Get(&cc)
	if err != nil {
		logwarp.Std().Warningln(err)
		return nil, SystemException
	}
	if !exist {
		logwarp.Std().Warningln("非法操作", uid, clubId)
		return nil, InvalidOptException
	}
	return &cc, nil
}

type UserInfoEntry struct {
	Id               string
	NickName         string
	Avatar           string
	No               string
	Title            string
	CurrentClubId    string
	CurrentClubName  string
	GamesInnings     int // 游戏总场数
	GamesWinInnings  int // 游戏获胜总场数
	NiuNiuInnings    int // 牛牛游戏总场数
	NiuNiuWinInnings int // 牛牛游戏获胜总场数
	NiuNiuWinRate    int // 牛牛游戏胜率
	Score            int // 总积分
	TitleDisPlay     int // 用户头像框的显示
}

type ClubInfoEntry struct {
	Id              string // 俱乐部Id
	No              string // 俱乐部编号
	Name            string // 俱乐部名称
	VipDays         int    // vip剩余天数
	HouseCards      int    // 当前房卡数
	Introduction    string // 简介
	VipTitleDisplay int    // 新增 该俱乐部下vip头像框显示
}
